<!--
 * @Description: 
 * @Author: wangyan
 * @Date: 2021-03-01 10:01:54
 * @LastEditTime: 2021-04-15 16:22:28
 * @LastEditors: @yzcheng
-->
<!--  -->
<template>
  <div class="search-form">
    <el-form
      :inline="true"
      :model="searchForm"
      size="large"
      class="demo-form-inline"
      ref="ruleForm"
    >
      <el-form-item label="流程名称">
        <el-input
          size="small"
          v-model="searchForm.processDefName"
          placeholder="流程名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="环节名称">
        <el-input
          size="small"
          v-model="searchForm.taskName"
          :placeholder="$t(`form.classificationName`)"
        ></el-input>
      </el-form-item>
      <el-form-item label="流程分类">
        <el-popover placement="bottom" :width="200" trigger="click">
          <el-tree :data="treeData" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
          <template #reference>
            <el-input size="small" v-model="searchForm.parName" clearable></el-input>
          </template>
        </el-popover>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          size="small"
          v-model="searchForm.date"
          type="daterange"
          range-separator="——"
          start-placeholder=""
          end-placeholder=""
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch" size="small">{{
          $t(`button.search`)
        }}</el-button>
        <el-button @click="resetForm('ruleForm')" size="small">{{ $t(`button.reset`) }}</el-button>
      </el-form-item>
    </el-form>
  </div>
  <Table
    :loading="loading"
    :columnData="columnData"
    :tableData="tableData"
    :othercolumnData="othercolumnData"
    :pageOption="pageOption"
  />
  <el-dialog v-model="dialogVisible" :append-to-body="true" destroy-on-close width="1200px">
    <Modal :data="ModalData" />
  </el-dialog>
  <el-dialog v-model="editVisible" destroy-on-close :close-on-click-modal="false" width="955x">
    <!-- <el-dialog
      width="30%"
      title="内层 Dialog"
      v-model="innerVisible"
      append-to-body
    > -->

    <Task
      v-if="innerVisible"
      :innerVisible="innerVisible"
      :type="taskType"
      :data="row"
      :closeFn="close"
      :fromType="fromType"
      :Generalrequest="Generalrequest"
      :searchTodoList="searchTodoList"
      :userCodeList="userCodeList"
    />
    <c-user-copies-dialog
      ref="userCopiesDialogRef"
      :submitCopies="submitCopies"
    ></c-user-copies-dialog>
    <iframe src="http://10.25.184.13:8080/form" width="500px" frameborder="0" ref="iframe"></iframe>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="success" @click="Task('FinishTask')">通过</el-button>
        <el-button
          type="info"
          v-if="authorityList?.findIndex((item) => item.name === '退回') !== -1"
          @click="backFlowVisible = true"
          >退回</el-button
        >
        <el-button
          type="danger"
          v-if="authorityList?.findIndex((item) => item.name === '退回起点') !== -1"
          @click="Task('rejectLast')"
        >
          退回起点
        </el-button>
        <el-button
          type="danger"
          v-if="authorityList?.findIndex((item) => item.name === '退回上一步') !== -1"
          @click="Task('reject')"
          >退回上一步</el-button
        >
        <el-button
          type="danger"
          v-if="authorityList?.findIndex((item) => item.name === '强制办结') !== -1"
          @click="Task('spreject')"
          >强制办结</el-button
        >
        <el-button
          type="primary"
          v-if="authorityList?.findIndex((item) => item.name === '转办') !== -1"
          plain
          @click="Task('transfer')"
          >转办</el-button
        >
        <el-button
          type="success"
          v-if="authorityList?.findIndex((item) => item.name === '委派') !== -1"
          plain
          @click="Task('delegateTask')"
          >委派</el-button
        >
        <el-button
          type="danger"
          v-if="authorityList?.findIndex((item) => item.name === '废弃') !== -1"
          @click="Task('abandoned')"
        >
          废弃
        </el-button>
        <el-button
          type="success"
          v-if="authorityList?.findIndex((item) => item.name === '意见征询') !== -1"
          plain
          @click="Task('delegateTask')"
          >意见征询</el-button
        >
        <el-button
          type="success"
          v-if="authorityList?.findIndex((item) => item.name === '抄送') !== -1"
          plain
          @click="openCopiesDialog"
          >抄送</el-button
        >
      </span>
    </template>
  </el-dialog>
  <!-- 退回流程 -->
  <back-flow v-if="backFlowVisible" v-model:visible="backFlowVisible" v-bind="row" />
</template>

<script>
import UserCopiesDialog from '@/components/bpmn/components/bpmnPropertiesPanel/components/generalFormComponents/userTaskComponents/GeneralComponents/UserCopiesDialog.vue'
import { mapActions, mapState } from 'vuex'
import Table from '../../components/Table.vue'
import { dateToMs, timestampToTime } from '../../utils/currency'
import Modal from '../historyList/component/Modal.vue'
import BackFlow from './components/BackFlow'
import Task from './components/Task.vue'

export default {
  name: 'TodoList',
  components: {
    Table,
    Modal,
    Task,
    BackFlow,
    'c-user-copies-dialog': UserCopiesDialog,
  },
  data() {
    return {
      loading: false,
      backFlowVisible: false,
      authorityList: [],
      searchForm: {},
      tableData: [],
      dialogVisible: false,
      editVisible: false,
      innerVisible: false,
      taskType: '',
      ModalData: {},
      Generalrequest: Function,
      fromType: 0,
      row: {},
      listCalssify: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      columnData: [
        { title: '当前环节', prop: 'taskName' },
        // { title: '实例名称', prop: 'processIntanceName' },
        // { title: '分配人员', prop: 'assignee' },
        {
          title: '创建时间',
          prop: 'createDate',
          // formatter: (row) => {
          //   return timestampToTime(row.createTime)
          // },
        },
      ],
      othercolumnData: [
        {
          title: '操作',
          prop: '操作',
          list: [
            { title: '流程追踪', fn: this.flowTrack,limit:'LCZX:LCBL:DBRW:FLOW' },
            { title: '编辑', fn: this.editFlow,limit:'LCZX:LCBL:DBRW:EDIT' },
          ],
        },
      ],
      pageOption: {
        pageNum: 1,
        pageChange: this.pageChange,
        total: 0,
      },
      userCodeList: [],
    }
  },

  //生命周期 - 创建完成（访问当前this实例）
  created() {
    window.addEventListener('message', this.receiveMessageFromIframePage, false)
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.searchTodoList({ pageOption: { pageNum: 1, pageSize: 10 } })
    this.getFlowList()
  },
  computed: {
    ...mapState({
      treeData: (state) => state.flowClassifyStore.treeData,
    }),
  },
  methods: {
    ...mapActions('todoListStore', [
      'pageTodoList',
      'startTask',
      'trunTask',
      'delegateTask',
      'backTask',
      'backFirstTask',
      'overTask',
      'saveCopies',
    ]),
    ...mapActions('flowClassifyStore', ['getFlowList']),
    ...mapActions('flowInstance', ['discardFlowRequest']),
    ...mapActions('historyListStore', ['finishTask']),
    receiveMessageFromIframePage(event) {
      if (event.data && event.data.data && event.data.data.type) {
        console.log()
      }
    },

    async searchTodoList(pageOption) {
      this.loading = true
      const res = await this.pageTodoList(pageOption)
      this.loading = false
      console.log(res,'pageTodoList');
      this.tableData = res.records
      this.pageOption.total = res.total
    },
    pageChange(val) {
      var data = Object.assign({}, this.searchForm)
      data = this.dataProcess(data)
      this.searchTodoList({
        pageOption: { pageNum: val, pageSize: 10 },
        data,
      })
    },
    flowTrack(index, row) {
      this.ModalData.processIntanceId = row.processIntanceId
      this.ModalData.processDefinitionId = row.processDefinitionId
      this.ModalData.taskDefinitionKey = row.taskDefinitionKey
      this.dialogVisible = true
    },
    editFlow(index, row) {
      this.editVisible = true
      this.authorityList = row?.customActivitiAttribute?.authorityList || []
      // console.log(`this.authorityList`, this.authorityList);
      this.row = row
      // console.log(this.$refs);
      // const mapFrame = this.$refs.iframe;
      // const iframeWin = mapFrame.contentWindow;
      // console.log("mapFrame.attachEvent", mapFrame);
      // if (mapFrame.attachEvent) {
      //   // eslint-disable-next-line
      //   mapFrame.attachEvent("onload", function () {
      //     iframeWin.postMessage(
      //       {
      //         //定义接收方法，方便精准接收
      //         iframeClick: "getParams",
      //         params: {
      //           //传递的值
      //           key: 111,
      //         },
      //       },
      //       "*"
      //     );
      //   });
      // } else {
      //   // eslint-disable-next-line
      //   mapFrame.onload = function () {
      //     iframeWin.postMessage(
      //       {
      //         iframeClick: "getParams",
      //         params: {
      //           key: 1111,
      //         },
      //       },
      //       "*"
      //     );
      //   };
      // }
    },

    handleNodeClick(data) {
      this.searchForm.parName = data.name
      this.searchForm.processCategories = data.id
    },
    resetForm() {
      this.searchForm = {}
    },
    onSearch() {
      var data = Object.assign({}, this.searchForm)
      data = this.dataProcess(data)

      this.searchTodoList({
        pageOption: { pageNum: 1, pageSize: 10 },
        data: data,
      })
    },
    dataProcess(data) {
      if (data.date && data.date.length > 0) {
        data.startTime = dateToMs(data.date[0])
        data.endTime = dateToMs(data.date[1])
        delete data.date
      }
      if (data.parName) {
        delete data.parName
      } else {
        delete data.parName
        delete data.processCategories
      }
      return data
    },

    async start() {
      await this.startTask()
      setTimeout(() => {
        this.searchTodoList({ pageOption: { pageNum: 1, pageSize: 10 } })
      }, 200)
    },
    reject(data) {
      this.backTask(data)
    },
    rejectLast(data) {
      this.backFirstTask(data)
    },
    spreject(data) {
      this.overTask(data)
    },
    DelegateTask(data) {
      this.delegateTask(data)
    },
    transfer(data) {
      this.trunTask(data)
    },
    abandoned({ processInstanceId, comment }) {
      //废弃流程
      this.discardFlowRequest({ processInstanceId, comment })
    },
    async FinishTask(data) {
      await this.finishTask(data)
    },
    Task(type) {
      this.innerVisible = true
      this.taskType = type
      switch (type) {
        case 'reject':
          this.fromType = 1
          this.Generalrequest = this.reject

          break
        case 'rejectLast':
          this.fromType = 1
          this.Generalrequest = this.rejectLast

          break
        case 'spreject':
          this.fromType = 1
          this.Generalrequest = this.spreject
          break
        case 'delegateTask':
          this.fromType = 2
          this.Generalrequest = this.DelegateTask
          break
        case 'transfer':
          this.fromType = 2
          this.Generalrequest = this.transfer
          break
        case 'FinishTask':
          this.fromType = 1
          this.Generalrequest = this.FinishTask
          break
        case 'abandoned':
          this.fromType = 1
          this.Generalrequest = this.abandoned
          break
        default:
          break
      }
    },
    // Yes(){},
    close() {
      this.innerVisible = false
      this.editVisible = false
    },
    // 开启设置抄送人对话框
    openCopiesDialog() {
      this.$refs.userCopiesDialogRef.visible = true
      this.userCodeList = []
    },
    // 保存抄送人信息
    submitCopies(data) {
      this.$refs.userCopiesDialogRef.visible = false
      this.userCodeList = data
    },
  },
}
</script>
<style scoped lang="scss">
/* @import url(); 引入scss类 */
.search-form {
  margin-top: 15px;
}
</style>
